//
//  ReturnCarViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/7/2.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit
import MAMapKit

class ReturnCarViewController: UIViewController {

    @IBOutlet weak var mapView: MAMapView!
    @IBOutlet weak var distanceLabel: UILabel!
    @IBOutlet weak var parkNameLabel: UILabel!
    @IBOutlet weak var parkInfoView: UIView!
    
    var order: Order.Detail?
    
    private var data: [Order.RecommendReturnList.Parking]!
    
    var location: CLLocation?
    var selectedPark: Order.RecommendReturnList.Parking!     //点击大头针选择上的停车场
    var first = true
    
    var stopPoint: Order.ReturnCar?
    
    var carPlateNumber: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.config()
        mapView.delegate = self
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        navigationController?.isNavigationBarHidden = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.isNavigationBarHidden = true
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func back(_ sender: UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    // MARK: - MAMapViewDelegate
    
    func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
        
        guard !updatingLocation else {
            return
        }
        
        guard first else {
            return
        }
        
        first = false

        if let location = userLocation.location {
            self.location = location

            let coordinate = location.coordinate
            JZLoading.showLoadingWith(toView: self.view)
            Order.recommendReturnList(location: coordinate, success: { park in
                JZLoading.hideLoading()
                if let data = park {
                    self.data = data
                }
                //开始添加大头针
                self.addAnnotations()
            }) { error in
                JZLoading.hideLoading()
                p(error)
            }
        }
    }
    
    @IBAction func confirmReturnCar(_ sender: UIButton) {
        if order?.orderType == 1 {
            self.performSegue(withIdentifier: "confirmReturnCarSegue", sender: nil)
        } else {
            self.performSegue(withIdentifier: "recardOilSence", sender: nil)
        }
    }
    
    @IBAction func guideMap(_ sender: Any) {        
        var lat: Double = 0.0
        var lon: Double = 0.0
        
        lat = Double(selectedPark.parkingLotLat)!
        lon = Double(selectedPark.parkingLotLng)!
        
        let array = Navigator.installApps()
        
        let actionSheet = UIAlertController(title: "选择导航软件", message: "", preferredStyle: .actionSheet)
        actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { [weak self] action in
            self?.dismiss(animated: true, completion: nil)
        }))
        
        for item in array {
            actionSheet.addAction(UIAlertAction(title: item.name, style: .default, handler: { action in
                switch item.index {
                case 0:
                    Navigator.gotoBaiduApp(lat, lon: lon)
                    
                case 1:
                    Navigator.gotoGaodeApp(lat, lon: lon )
                    
                case 2:
                    Navigator.gotoSystemMap(lat, lon: lon)
                default:break
                }
            }))
        }
        present(actionSheet, animated: true, completion: nil)
    }
    
    func addAnnotations() {
        //添加之前移除所有的大头针
        mapView.removeAnnotations(self.mapView.annotations)
        
        for item in data {
            if let lat = Double(item.parkingLotLat), let lon = Double(item.parkingLotLng) {
                let park = ParkingAnnotation(id: item.parkingLotId, carNum: item.carNum)
                
                park.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                park.parkingLat = Double(item.parkingLotLat)
                park.parkingLon = Double(item.parkingLotLng)
                park.parkingDistance = Int(item.parkingLotDistance)
                park.parkName = item.parkName
                park.spaceCount = Int(item.spaceNum)
                park.signType = item.signType
                park.fenceFlag = item.fenceFlag
                park.radius = item.radius
                park.coordinates = item.lngLats
                mapView.addAnnotation(park)
            }
        }
    }
    
    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "confirmReturnCarSegue" {
            if let vc = segue.destination as? ConfirmReturnCarViewController {
                vc.order = order
                vc.location = location
            }
        } else if segue.identifier == "recardOilSence" {
            if let vc = segue.destination as? OilRecordViewController {
                vc.order = order
                vc.location = location
            }
        }
    }
}

extension ReturnCarViewController: MAMapViewDelegate {
    
    //自定义大头针视图
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        let identifiter = "parkAnnoticationIdent"
        var parkannotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: identifiter)
        
        if annotation.isKind(of: ParkingAnnotation.self) {
            if parkannotationView == nil {
                if let parkAnnotation = annotation as? ParkingAnnotation {
                    if parkAnnotation.signType == .signed {
                        parkannotationView = ParkingAnnotationView(annotation: annotation, reuseIdentifier: identifiter, num: parkAnnotation.carNum)
                    } else {
                        parkannotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: identifiter)
                        parkannotationView?.image = UIImage(named: "parkIcon")
                    }
                }
            }
        }
        return parkannotationView
    }
    
    func contentInfo(_ park: ParkingAnnotation) {
        parkInfoView.isHidden = false
        parkNameLabel.text = park.parkName
        
        guard let distance = park.parkingDistance else {
            return
        }
        
        if let count = park.spaceCount {
            distanceLabel.text = "\(distance)米   当前剩余停车位\(count)"
        } else {
            distanceLabel.text = "\(distance)米"
        }
    }
    func draw(_ park: ParkingAnnotation) {
        
        //显示导航条内容
        contentInfo(park)
        
        if park.fenceFlag == 1 {
            if let coordinates = park.coordinates {
                var coords = [CLLocationCoordinate2D]()
                for arr in coordinates {
                    if let lat = Double(arr[1]), let lon = Double(arr[0]) {
                        let a = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                        coords.append(a)
                    }
                }
                let pol: MAPolygon = MAPolygon(coordinates: &coords, count: UInt(coords.count));mapView.add(pol)
            }
            
        } else if park.fenceFlag == 2 {
            
            if let lat = park.parkingLat, let lon = park.parkingLon, let radius = Double(park.radius!) {
                let pol: MACircle = MACircle(center: CLLocationCoordinate2D(latitude: lat, longitude: lon ), radius: radius)
                mapView.add(pol)
            }
        }
    }
        
    
    //点击大头针
    func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) {
        if view.annotation.isKind(of: ParkingAnnotation.self) {
            let annotation: ParkingAnnotation = view.annotation as! ParkingAnnotation
            for item in data {
                if item.parkingLotId == annotation.id {
                    selectedPark = item
                    draw(annotation)
                    break
                }
            }
        }
    }
    
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        
        if overlay.isKind(of: MAPolygon.self) {
            
            guard let polygon = MAPolygonRenderer(overlay: overlay) else {
                return nil
            }
            polygon.lineDashType = .dot
            polygon.lineWidth = 5.0
            polygon.strokeColor = UIColor(red: 254.00 / 255.00, green: 112.00 / 255.00, blue: 59.00 / 255.00, alpha: 1.0)
            polygon.fillColor = UIColor(red: 255.00 / 255.00, green: 117.00 / 255.00, blue: 23.00 / 255.00, alpha: 0.25)
            polygon.lineJoinType = kMALineJoinRound
            polygon.lineCapType = kMALineCapRound
            return polygon
        } else if overlay.isKind(of: MACircle.self) {
            
            guard let circle = MACircleRenderer(overlay: overlay) else {
                return nil
            }
            circle.lineDashType = .dot
            circle.lineWidth = 5.0
            circle.strokeColor = UIColor(red: 254.00 / 255.00, green: 112.00 / 255.00, blue: 59.00 / 255.00, alpha: 1.0)
            circle.fillColor = UIColor(red: 255.00 / 255.00, green: 117.00 / 255.00, blue: 23.00 / 255.00, alpha: 0.25)
            circle.lineJoinType = kMALineJoinRound
            circle.lineCapType = kMALineCapRound
            return circle
        }
        
        return nil
    }

}
